using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using LoanApprovalClient.LoanDataService;
using LoanApprovalClient.CustomerService;
using LoanApprovalClient.LoanCalculationService;
using au.Swindles;

namespace LoanApprovalClient
{
    public partial class AdminApprove : System.Web.UI.Page
    {
        private string sessionKey;
        BLApproveAdmin.BLApproveAdmin blApproveAdmin = new LoanApprovalClient.BLApproveAdmin.BLApproveAdmin();
        List<LoanApprovalClient.LoanDataService.Application> apps
        {
            get {
                string key = "APPLIST" + sessionKey;
                return Cache[key] as List<LoanApprovalClient.LoanDataService.Application>;
            }
            set
            {
                string key = "APPLIST" + sessionKey;
                if (Cache[key] != null)
                {
                    Cache.Remove(key);
                }else{
                    Cache.Add(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), System.Web.Caching.CacheItemPriority.Default, null); 
                }
                
            }
        }

        LoanApprovalClient.LoanDataService.Application currentApp
        {
            get
            {
                string key = "CURRENTAPP" + sessionKey;
                return Cache[key] as LoanApprovalClient.LoanDataService.Application;
            }
            set
            {
                string key = "CURRENTAPP" + sessionKey;
                if (Cache[key] != null)
                {
                    Cache.Remove(key);
                }
                else
                {
                    Cache.Add(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), System.Web.Caching.CacheItemPriority.Default, null);
                }

            }
        }



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            // By default, the main data is not rendered.
            divMainData.Visible = false;
            divUserNotLoggedIn.Visible = true;
            blApproveAdmin.currentPage = this.Page;
            lblInfoMessage.Text = string.Empty;
            this.PreRender += new EventHandler(AdminApprove_PreRender);
            grdApps.ItemDataBound += new DataGridItemEventHandler(grdApps_ItemDataBound);
            btnReject.Command += new CommandEventHandler(btnReject_Command);
            btnApprove.Command += new CommandEventHandler(btnApprove_Command);
        }

        void btnApprove_Command(object sender, CommandEventArgs e)
        {
            // Approve Application
            try
            {
                Application app = blApproveAdmin.getLoanApplication(Convert.ToInt32(txtApplicationID));
                Customer customer = blApproveAdmin.getCustomer(app.CustomerID);
                Quote quote = blApproveAdmin.getQuote(app.QuoteID);
                saveFields(ref app,ref customer, ref quote);
                blApproveAdmin.approveLoanApplication(ref app, ref customer, ref quote);
                loadApplicationList();
            }
            catch (Exception pEx)
            {
                addToInfoMessage("There was a problem retrieving the Loan Application data to processing. Please try again later.");
            }

        }

        private void saveFields(ref Application app, ref Customer customer, ref Quote quote)
        {
            // Update customer
            // Update quote 
            // Update loan applciation
            customer.CreditRating = Convert.ToInt32(txtCreditRating.Text);
            app.Comments = txtCommentsNew.Text;

            quote.LoanAmount = Convert.ToDecimal( txtLoanAmount.Text );
            quote.LoanIntrest =Convert.ToDecimal(  txtLoanIntrest.Text);
            quote.LoanTerm = Convert.ToInt32( txtLoanTerm.Text);
            quote.LoanInsurance = txtLoanInsurance.Text;
            quote.LoanMRepayment = Convert.ToDecimal( txtLoanMRepayment.Text);

        }

        void btnReject_Command(object sender, CommandEventArgs e)
        {
            // Reject Application
            try
            {
                Application app = blApproveAdmin.getLoanApplication(Convert.ToInt32(txtApplicationID));
                Customer customer = blApproveAdmin.getCustomer(app.CustomerID);
                Quote quote = blApproveAdmin.getQuote(app.QuoteID);
                saveFields(ref app, ref customer, ref quote);
                blApproveAdmin.rejectLoanApplication(ref app, ref customer, ref quote);
                loadApplicationList();
            }
            catch (Exception pEx)
            {
                addToInfoMessage("There was a problem retrieving the Loan Application data to processing. Please try again later.");
            }
        }

        void grdApps_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            Control hidControl = e.Item.FindControl("hidLoanAppID");
            if ( null != hidControl ){
                if (e.Item.DataItem != null)
                {
                    ((HiddenField)hidControl).Value = (e.Item.DataItem as LoanApprovalClient.LoanDataService.Application).ApplicationID.ToString();
                }
                else {
                    ((HiddenField)hidControl).Value = 0.ToString();
                }
            }
        }

        void AdminApprove_PreRender(object sender, EventArgs e)
        {
            // make non editable fields readonly
            txtApplicationID.ReadOnly = true;
            txtAnnualIncome.ReadOnly = true;
            txtApplicationStatus.ReadOnly = true;
            txtAssetValue.ReadOnly = true;
            txtStatusUpdateDate.ReadOnly = true;
            txtAnnualExpense.ReadOnly = true;
            txtStatusUpdateUserID.ReadOnly = true;
            txtComments.ReadOnly = true;

            txtCusomerID.ReadOnly = true;
            txtCustomerNumber.ReadOnly = true;
            txtCustomerName.ReadOnly = true;
            txtEmail.ReadOnly = true;
            txtPassword.ReadOnly = true;
            txtReason.ReadOnly = true;
            txtPrptyAddressLine1.ReadOnly = true;
            txtPrptyType.ReadOnly = true;
            txtPrptyAddressLine2.ReadOnly = true;
            txtPrptySize.ReadOnly = true;
            txtPrptySuburb.ReadOnly = true;
            txtPrptyYearBuilt.ReadOnly = true;
            txtPrptyState.ReadOnly = true;
            txtPrptyValue.ReadOnly = true;
            txtPrptyPostcode.ReadOnly = true;
            
            // Editable fields
            txtCreditRating.ReadOnly = false;
            txtCommentsNew.ReadOnly = false;

            txtLoanAmount.ReadOnly = false;
            txtLoanIntrest.ReadOnly = false;
            txtLoanTerm.ReadOnly = false;
            txtLoanInsurance.ReadOnly = false;
            txtLoanMRepayment.ReadOnly = false;
            txtQuoteDate.ReadOnly = false;

        }

        protected void grdApps_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if ( e.CommandName=="btnAppProcess"){
                int loanAppID = Utilities.getInt32(((HiddenField)e.Item.FindControl("hidLoanAppID")).Value);
                showLoanAppDetails(loanAppID);
            }
        }

        private void showLoanAppDetails(int loanAppID)
        {
            bool errors = false;
            // Get loan app details
            Application app = blApproveAdmin.getLoanApplication(loanAppID);
            Customer customer = null;
            Quote quote = null;
            if (app != null)
            {
                // Get Customer details
                customer = blApproveAdmin.getCustomer(app.CustomerID);
                if (null == customer)
                {
                    addToInfoMessage("There was a problem retriving the Customer information. Pleasse try again later.");
                    errors = true;
                }
                else
                {
                    // Get Quote details
                    quote = blApproveAdmin.getQuote(app.QuoteID);
                    if (null == quote)
                    {
                        addToInfoMessage("There was a problem retriving the Quote information. Pleasse try again later.");
                        errors = true;
                    }
                }
            }
            else
            {
                addToInfoMessage("There was a problem retriving the Loan Application. Pleasse try again later.");
                errors = true;
            }

            // Load Loan info
            if (null != app)
            {
                txtApplicationID.Text = Convert.ToString(app.ApplicationID);
                txtAnnualIncome.Text = Convert.ToString( app.AnnualIncome);
                txtApplicationStatus.Text = app.ApplicationStatus;
                txtAssetValue.Text = Convert.ToString( app.AssetValue);
                txtStatusUpdateDate.Text = app.StatusUpdateDate.ToShortDateString();
                txtAnnualExpense.Text = Convert.ToString( app.AnnualExpense);
                txtStatusUpdateUserID.Text = Convert.ToString( app.StatusUpdateUserID);
                txtComments.Text = app.Comments;

                btnApprove.CommandArgument = Convert.ToString(app.ApplicationID);
                btnReject.CommandArgument = Convert.ToString(app.ApplicationID);
            }
            // Load Customer info
            if (null != customer)
            {
                txtCusomerID.Text = Convert.ToString( customer.CusomerID);
                txtCustomerNumber.Text = customer.CustomerNumber;
                txtCustomerName.Text = customer.CustomerName;
                txtEmail.Text = customer.Email;
                txtCreditRating.Text = Convert.ToString( customer.CreditRating);
                txtPassword.Text = customer.Password;
                txtReason.Text = customer.Reason;
            }

            // Load Quote info
            if (null != quote)
            {
                txtPrptyAddressLine1.Text = quote.PrptyAddressLine1;
                txtPrptyType.Text = quote.PrptyType;
                txtPrptyAddressLine2.Text = quote.PrptyAddressLine2;
                txtPrptySize.Text = Convert.ToString( quote.PrptySize);
                txtPrptySuburb.Text = quote.PrptySuburb;
                txtPrptyYearBuilt.Text = Convert.ToString( quote.PrptyYearBuilt);
                txtPrptyState.Text = quote.PrptyState;
                txtPrptyValue.Text = Convert.ToString( quote.PrptyValue);
                txtPrptyPostcode.Text = Convert.ToString( quote.PrptyPostcode);
                txtLoanAmount.Text = Convert.ToString( quote.LoanAmount);
                txtLoanIntrest.Text = Convert.ToString( quote.LoanIntrest);
                txtLoanTerm.Text = Convert.ToString( quote.LoanTerm);
                txtLoanInsurance.Text = quote.LoanInsurance;
                txtLoanMRepayment.Text = Convert.ToString( quote.LoanMRepayment);
                txtQuoteDate.Text = Convert.ToString( quote.QuoteDate);
            }


        }

        private void addToInfoMessage(string pMessage){
            lblInfoMessage.Visible = true;
            lblInfoMessage.Text += pMessage + "<br>";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Check if the user is logged in
            sessionKey = this.Request.QueryString["s"];
            if (!blApproveAdmin.checkIfUserLoggedIn(sessionKey))
            {
                divMainData.Visible = false;
                divUserNotLoggedIn.Visible = true;
            }
            else
            {
                divMainData.Visible = true;
                divUserNotLoggedIn.Visible = false;
            }

            // Render the Pending applications on the screen.
            if (!this.IsPostBack)
            {
                loadApplicationList();
            }

        }

        private void loadApplicationList()
        {
            List<Application> apps = blApproveAdmin.getPendingApplications();
            grdApps.DataSource = apps;
            grdApps.DataBind();
        }
    }
}
